﻿Imports System.Globalization

Partial Public Class Release_Credit_Limit
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not (IsPostBack) Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "RELEASE SALE ORDER "
            LoadCreditBlock()
        End If
    End Sub

    Private Sub LoadCreditBlock()
        Dim dt As DataTable = clsGet.GetBlock_CreditLimit()
        If (dt.Rows.Count > 0) Then
            lbAlert.Visible = False
            'ทำการ Connect SAP
            Dim Credit_Limit As SAP_IPORT.ZBAPI_CREDIT_LIMITEDTable = GetCreditLimit(dt)
            If (Credit_Limit.Count > 0) Then
                ViewState("Credit_Limit") = Credit_Limit
                gridCreditLimit.DataSource = dt
                gridCreditLimit.DataBind()
            End If
        Else
            lbAlert.Visible = True
            ViewState("Credit_Limit") = Nothing
            gridCreditLimit.DataSource = Nothing
            gridCreditLimit.DataBind()
            lbAlert.Text = "ไม่พบรายการ Credit Limit ที่ต้องทำการปลดบล็อค"
        End If
        ViewState("Credit") = dt
    End Sub

    Private Function GetCreditLimit(ByVal dt As DataTable) As SAP_IPORT.ZBAPI_CREDIT_LIMITEDTable
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        Dim IM_CR_AREA As String = "1004"
        Dim EX_SUBRC As Integer

        Dim Input_Value As SAP_IPORT.ZBAPI_LIMITED_INPUT
        Dim Input_Table As New SAP_IPORT.ZBAPI_LIMITED_INPUTTable
        For Each dr As DataRow In dt.Rows
            If (dr.Item("Sold_To") & "" <> "") Then
                Input_Value = New SAP_IPORT.ZBAPI_LIMITED_INPUT
                Input_Value.Customer = dr.Item("Sold_To")
                Input_Table.Insert(0, Input_Value)
            End If
        Next

        Dim CR_Limit As New SAP_IPORT.ZBAPI_CREDIT_LIMITEDTable
        Try
            SAP_Data.Zbapi_Iport_Cr_Limited_Master(IM_CR_AREA, EX_SUBRC, CR_Limit, Input_Table)
        Catch ex As Exception
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('พบปัญหาเกี่ยวกับการเชื่อมต่อกับ SAP !!');", True)
        End Try
        Return CR_Limit
        ClassSAP.SAP_CLOSE(SAP_Data)
    End Function

    Private Function GenHTML_Credit_Limit(ByVal Credit As SAP_IPORT.ZBAPI_CREDIT_LIMITED, ByVal Iport_no As String, ByVal Booking_no As String, ByVal Vessel As String, ByVal TypePay As String, ByVal SaleOrder As String, ByVal SaleOrderCreate As String, ByVal CreditText As String) As String
        Dim HTML As String = ""
        HTML = "<table width='100%' style='border-width: 0px;' border='0' cellpadding='2' cellspacing='0'>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Booking No. :</font>&nbsp;</td>"
        HTML &= "<td colspan='5' align='left'><font class='White-Style' style='color:#000000'>" & Booking_no & "</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Customer :</font>&nbsp;</td>"
        HTML &= "<td colspan='5' align='left'><font class='White-Style' style='color:#000000'>" & clsGet.GetName_Customer(Credit.Customer) & "</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Ship Name :</font>&nbsp;</td>"
        HTML &= "<td colspan='5' align='left'><font class='White-Style' style='color:#000000'>" & Vessel & "</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Type Payment :</font>&nbsp;</td>"
        HTML &= "<td colspan='5' align='left'><font class='White-Style' style='color:#000000'>" & TypePay & "</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Sale Order No. :</font>&nbsp;</td>"
        HTML &= "<td style='width:150px;' align='left'><font class='White-Style' style='color:#000000'>" & SaleOrder & "</font>&nbsp;</td>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Create Sale Order :</font>&nbsp;</td>"
        HTML &= "<td colspan='3' align='left'><font class='White-Style' style='color:#000000'>" & CDate(SaleOrderCreate.Substring(6, 2) & "/" & SaleOrderCreate.Substring(4, 2) & "/" & SaleOrderCreate.Substring(0, 4)).ToString("dd.MM.") & SaleOrderCreate.Substring(0, 4) & "</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        If (TypePay = "Credit Sale") Then
            HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Credit Value :</font>&nbsp;</td>"
        Else
            HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Cash Value :</font>&nbsp;</td>"
        End If
        HTML &= "<td style='width:150px;' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(clsGet.GetMoneySumNet(Iport_no), 2) & " THB</font>&nbsp;</td>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Vat :</font>&nbsp;</td>"
        HTML &= "<td colspan='3' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(CDbl(clsGet.GetMoneySumNet(Iport_no)) * 0.07, 2) & " THB</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Total :</font>&nbsp;</td>"
        HTML &= "<td colspan='5' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(CDbl(clsGet.GetMoneySumNet(Iport_no)) + (CDbl(clsGet.GetMoneySumNet(Iport_no)) * 0.07), 2) & " THB</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Status :</font>&nbsp;</td>"
        HTML &= "<td colspan='5' align='left'><font class='White-Style' style='color:#FF0000'>" & CreditText & "</font>&nbsp;</td>"
        HTML &= "</tr>"
        HTML &= "</table>"


        HTML &= "<table width='100%' style='border-width: 0px;' border='0' cellpadding='2' cellspacing='0'>"
        HTML &= "<tr><td colspan='6' align='center'>"
        ' HTML &= "<fieldset style='border-color: red;'><table width='95%' style='border-width: 0px;' border='0' cellpadding='2' cellspacing='0'>"
        HTML &= "<fieldset><table width='95%' style='border-width: 0px;' border='0' cellpadding='2' cellspacing='0'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Credit Limit :</font>&nbsp;</td>"
        HTML &= "<td style='width:150px;' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(Credit.Cred_Limit, 2) & " THB</font>&nbsp;</td>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Credit Use :</font>&nbsp;</td>"
        HTML &= "<td colspan='3' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(Credit.Cred_Used, 2) & " THB</font>&nbsp;</td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Sales Value :</font>&nbsp;</td>"
        HTML &= "<td style='width:150px;' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(Credit.Sales_Val, 2) & " THB</font>&nbsp;</td>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Total receivables :</font>&nbsp;</td>"
        HTML &= "<td colspan='3' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(Credit.Recbl_Vals, 2) & " THB</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:130px;' align='right'><font class='White-Style' style='color:#000000'>Credit Available :</font>&nbsp;</td>"
        HTML &= "<td colspan='5' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(Credit.Cred_Availb, 2) & " THB</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "</table></fieldset></td></tr>"

        HTML &= "</table>"



        Return HTML
    End Function

    Private Sub gridCreditLimit_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridCreditLimit.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridCreditLimit.PageIndex <> 0) Then
            Index = Index Mod (gridCreditLimit.PageIndex * 10)
        End If
        If (e.CommandName = "cmdRelease") Then
            Dim ClassSAP As New Class_SAP

            Dim TB_MESSAGE As New SAP_IPORT.BAPIRET1Table
            Dim SO_INPUT As New SAP_IPORT.ZBAPI_SO_INPUTTable
            Dim SO_IN As SAP_IPORT.ZBAPI_SO_INPUT
            Try
                Dim SAP_Data As Object = ClassSAP.SAP_OPEN()


                SO_IN = New SAP_IPORT.ZBAPI_SO_INPUT
                SO_IN.Doc_Number = gridCreditLimit.DataKeys(Index).Values("EX_SALES_NO")
                SO_INPUT.Insert(0, SO_IN)

                SAP_Data.Zbapi_Iport_Release_Cr_Limited(TB_MESSAGE, SO_INPUT)
                ClassSAP.SAP_CLOSE(SAP_Data)
            Catch ex As Exception
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
                Exit Sub
            End Try
            'ทำการออก Billing ต่อ
            Dim EX_SALES_NO As String = ""
            Dim EX_BILL_NO As String = ""
            Dim EX_BUKRS As String = ""
            Dim EX_BELNR As String = ""
            Dim EX_GJAHR As String = ""
            Dim BABITable As New SAP_IPORT.BAPIRET1Table
            Dim EventSAP As String = ""
            Dim Bill_Date As String = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))
            Try
                Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
                Dim BABIHEADER As New SAP_IPORT.ZBAPI_SALES_HEADER
                Dim BABIONETIME As New SAP_IPORT.ZBAPI_SALES_ONETIME
                Dim SALE_TABLE As New SAP_IPORT.ZBAPI_SALES_ITEMSTable

                Dim MarkX As String = ""
                If (gridCreditLimit.DataKeys(Index).Values("Doc_Type") & "" = "ZSRR") Then
                    Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(gridCreditLimit.DataKeys(Index).Values("Booking_no"))
                    If (dsBooking.Tables(0).Rows(0).Item("Payin") & "" = "0") Then
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales("", gridCreditLimit.DataKeys(Index).Values("Iport_no"), BABIONETIME, BABIHEADER, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE)
                    Else
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales("X", gridCreditLimit.DataKeys(Index).Values("Iport_no"), BABIONETIME, BABIHEADER, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE)
                    End If

                    EventSAP = "Zbapi_Iport_Sd_Proc_Cr_Sales"
                Else
                    Dim dtemp As DataTable = clsGet.Get_SaleORDER_IPort_NumberFor_ReleseCashSale(gridCreditLimit.DataKeys(Index).Values("Iport_no"))
                    If (dtemp.Rows.Count = 1) Then

                        BABIHEADER.Doc_Type = dtemp.Rows(0).Item("Doc_Type")
                        BABIHEADER.Req_Date_H = dtemp.Rows(0).Item("Req_Date_H")
                        BABIHEADER.Sold_To = dtemp.Rows(0).Item("Sold_To")
                        BABIHEADER.Bill_To = dtemp.Rows(0).Item("Bill_To")
                        BABIHEADER.Ship_Name = dtemp.Rows(0).Item("Ship_Name")
                        BABIHEADER.Division = dtemp.Rows(0).Item("Division")

                        SAP_Data.Zbapi_Iport_Sd_Proc_Cash_Sales("", gridCreditLimit.DataKeys(Index).Values("Iport_no"), BABIONETIME, BABIHEADER, EX_BELNR, EX_BILL_NO, EX_BUKRS, EX_GJAHR, EX_SALES_NO, BABITable, SALE_TABLE)
                        EventSAP = "Zbapi_Iport_Sd_Proc_Cash_Sales"
                    End If


                End If
                ClassSAP.SAP_CLOSE(SAP_Data)
            Catch ex As Exception
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
                Exit Sub
            End Try

            If ((EX_BILL_NO <> "") Or (EX_BUKRS <> "") Or (EX_BELNR <> "")) Or (EventSAP = "Zbapi_Iport_Sd_Proc_Cr_Sales") Then
                Dim clsDB As New ClassDatabase()
                Dim clsFc As New ClassFunction()
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                If (clsFc.UPDATEBooking_Credit_limit(gridCreditLimit.DataKeys(Index).Values("Booking_no"), conn, tran) > 0) Then
                    If (clsFc.UPDATESale_Order(gridCreditLimit.DataKeys(Index).Values("Booking_no"), gridCreditLimit.DataKeys(Index).Values("Iport_no"), EX_SALES_NO, EX_BILL_NO, EX_BUKRS, EX_BELNR, EX_GJAHR, Bill_Date, conn, tran) > 0) Then
                        If (clsFc.InsertBooking_Credit_limit(gridCreditLimit.DataKeys(Index).Values("Booking_no"), gridCreditLimit.DataKeys(Index).Values("Iport_no"), gridCreditLimit.DataKeys(Index).Values("EX_SALES_NO"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), conn, tran) < 1) Then
                            condition = False
                        End If
                    End If
                Else
                    condition = False
                End If

                For Each dr As SAP_IPORT.BAPIRET1 In TB_MESSAGE
                    If (clsFc.InsertSAP_Table_MESSAGE(gridCreditLimit.DataKeys(Index).Values("Iport_no"), "Zbapi_Iport_Release_Cr_Limited", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                        condition = False
                    End If
                Next
                For Each dr As SAP_IPORT.BAPIRET1 In BABITable
                    If (clsFc.InsertSAP_Table_MESSAGE(gridCreditLimit.DataKeys(Index).Values("Iport_no"), EventSAP, dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                        condition = False
                    End If
                Next
                If (condition) Then
                    clsDB.CommitTran(tran)
                    LoadCreditBlock()
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการ Release สำเร็จ ');", True)
                Else
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการทำการ Release ');", True)
                End If
                Application.UnLock()
                conn.Dispose()
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
            End If

        End If
    End Sub

    Private Sub gridCreditLimit_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridCreditLimit.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim Li As Literal = CType(e.Row.FindControl("LiCredit"), Literal)
            Dim credit As SAP_IPORT.ZBAPI_CREDIT_LIMITEDTable = ViewState("Credit_Limit")
            For Each dr As SAP_IPORT.ZBAPI_CREDIT_LIMITED In credit
                If (CInt(dr.Customer) = CInt(gridCreditLimit.DataKeys(e.Row.RowIndex).Values("Sold_To"))) Then
                    Dim Type As String = ""
                    If (gridCreditLimit.DataKeys(e.Row.RowIndex).Values("Doc_Type") & "" = "ZSRC") Then
                        Type = "Cash Sale"
                    Else
                        Type = "Credit Sale"
                    End If

                    Li.Text = GenHTML_Credit_Limit(dr, gridCreditLimit.DataKeys(e.Row.RowIndex).Values("Iport_no"), gridCreditLimit.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridCreditLimit.DataKeys(e.Row.RowIndex).Values("Ship_Name"), Type, gridCreditLimit.DataKeys(e.Row.RowIndex).Values("EX_SALES_NO"), gridCreditLimit.DataKeys(e.Row.RowIndex).Values("Req_Date_H"), gridCreditLimit.DataKeys(e.Row.RowIndex).Values("MESSAGE"))
                    Exit For
                End If
            Next
        End If
    End Sub

    Private Sub gridCreditLimit_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridCreditLimit.RowEditing

    End Sub

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub
End Class